#!/bin/bash

set -e

initialize_repo() {
  # install
  if [ ! -d $ZMICRO_HOME ]; then
    git clone $ZMICRO_GIT -b $ZMICRO_VERSION $ZMICRO_HOME
    # git clone $ZMICRO_GIT -b master $ZMICRO_HOME
  # else
  #   log::info "[initailize] installed before (3), if you want to update, run 'zmicro update'"
  fi
}

initialize_config() {
  PATH=$ZMICRO_BIN_PATH:$PATH
  zmicro config rc

  zmicro config version
  zmicro config logs
  zmicro config data
  # zmicro config git
  # zmicro config timezone

    # Do for MacOS
  if [ "$(os::is_macos)" != "true" ]; then
    zmicro config locale
    zmicro config timezone
  fi

  # $ZMICRO_BIN_PATH/zmicro config git $USER $USER"@local"
  local origin_user=$(git config --get user.name)
  local origin_email=$(git config --get user.email)
  zmicro config git $origin_user $origin_email
}

initialize_depdendencies() {
  # install dependency plugins ...
  require::core_mod $@
}

help() {
  echo "update zmicro"
  echo ""
  echo "Usage:"
  echo "  zmicro update [...options]"
  echo "    -p, --plugin <plugin_name | all>    Update all or one plugin"
  echo "    -a, --all   Update core and all plugins"
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2
    case $key in
      -h | --help)
        help
        exit 0
        ;;
      -u | --update)
        os::set_var is_plugin_update true
        shift
        ;;
      *)
        if [ "$(string::match $key ^-)" = "true" ]; then
          echo "ERROR: unknown parameter \"$key\""
          help
          exit 1
        fi

        shift
        ;;
    esac
  done

  initialize_repo
  initialize_config

  if [ "$is_plugin_update" = "true" ]; then
    initialize_depdendencies -u
  else
    initialize_depdendencies
  fi

  # @TODO add auto update
  zmicro auto update 
}

run() {
  core $@
}

run $@

